<!-- 编目审核 -->
<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  NInput,
  NSelect,
  NSpace,
  NDatePicker,
  NTreeSelect,
  NModal,
  type FormRules,
  type DataTableColumns,
  type SelectOption,
  NTooltip
} from 'naive-ui'
import { h, ref, reactive, watch, type VNode, onMounted,onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
const message = useMessage()
const route = useRoute()
const form = reactive({
  itemName: null,
  collectTypeCode: null, //征集方式
  assessStatusCode: null, //编目审核状态
  laidStatusCode: null, //入库审核状态
  recipient:null,
  assetCode: null,
  timeRange: null, //日期范围选择
  reviewType: null, //审核类型
  batchCode: null, //批次
  itemTypeCode: null, //版本
  catalogStatusCode: null,
  storageStatusCode: null //入藏状态
})
const reasonContent = ref()
const renderOption = ref(({ node, option }: { node: VNode; option: SelectOption }) =>
  h(NTooltip, null, {
    trigger: () => node,
    default: () => option.classificationName
  })
)
const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    type: 'selection',
    width: '1rem'
  },
  // {
  //   title: '序号',
  //   key: 'index',
  //   width: '5rem',
  //   align: 'center',
  //   render: (e, index) => {
  //     return paginationReactive.pageSize * (paginationReactive.page - 1) + index + 1
  //   }
  // },
  {
    title: '批次编号',
    key: 'batchCode',
    width: '8rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '资产码',
    key: 'assetCode',
    width: '10rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '藏品名称',
    key: 'itemName',
    width: '10rem',
    align: 'center',
    // ellipsis: {
    //   tooltip: true
    // }
  },
  {
    title: '版本类型',
    key: 'itemTypeName',
    width: '10rem',
    align: 'center',
  },
  {
    title: '征集方式',
    key: 'collectTypeName',
    width: '5rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '领取人',
    key: 'catalogPeople',
    width: '5rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }  
  },
  {
    title: '编目审核状态',
    key: 'assessStatusName',
    width: '5rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '入库审核状态',
    key: 'laidStatusName',
    width: '5rem',
    align: 'center'
  }, 
  {
    title: '入藏状态',
    key: 'storageStatusName',
    width: '5rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  // {
  //   title: '编目状态',
  //   key: 'catalogStatusName',
  //   width: '10rem',
  //   align: 'center',
  //   ellipsis: {
  //     tooltip: true
  //   }
  // },
  {
    title: '操作',
    key: 'action',
    width: '10rem',
    align: 'center',
    render: (e: any) => [
      // 编目审核状态为审批中：审核、详情按钮
// 编目审核状态为通过：审核退回、编辑、入库、详情
// 编目审核状态为拒绝或审核退回：详情
// 入库审核状态为审批中：详情
// 入库审核状态为拒绝：审核退回、编辑、入库、详情
      // h(
      //   NButton,
      //   {
      //     type: 'primary',
      //     quaternary: true,
      //     style:{display:e?.ifMeFirstAudit?'inline':'none'},
      //     onClick: () => {
      //       router.push({
      //         path: '/collection/process/stepPlan/startApproveCon',
      //         query: { id: e.id, typeShow: 1, code: e?.subItemCode } //1初审 2终审
      //       })
      //     }
      //   },
      //   {
      //     default: () => '初审'
      //   }
      // ),
      // h(
      //   NButton,
      //   {
      //     type: 'primary',
      //     quaternary: true,
      //     style: { display: e?.ifMeFinalAudit ? 'inline' : 'none' },
      //     onClick: () => {
      //       router.push({
      //         path: '/collection/process/stepPlan/startApproveCon',
      //         query: { id: e.id, typeShow: 2, code: e?.subItemCode }
      //       })
      //     }
      //   },
      //   {
      //     default: () => '终审'
      //   }
      // ),
       h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          // assessStatusCode 编目审核状态 A5010 审批中  A5011 通过
          style: { display: e?.reviewFlag? 'inline' : 'none' },
          onClick: () => {
            router.push({
              path: '/collection/process/stepPlan/startApproveCon',
              query: { id: e.id, typeShow: 1, code: e?.subItemCode,redirect: router.currentRoute.value.fullPath }
            })
          }
        },
        {
          default: () => '审核'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          // inventoryReviewCode 入库审核状态  A6703拒绝
          style: {
            display: e.reviewReturn ? 'inline' : 'none'
          },

          onClick: () => {
            router.push({
              path: '/collection/process/stepPlan/startApproveConBack',
              query: { id: e.id, typeShow: 2, code: e?.subItemCode,redirect: router.currentRoute.value.fullPath }
            })
          }
        },
        {
          default: () => '审核退回'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: {
            display: e.edit ? 'inline' : 'none'
          },
          onClick: () => {
            router.push({
              path: '/collection/process/StepPlan/menu',
              query: { id: e.subItemCode, type: 1, code: e?.itemCode, idCopy: e?.id,redirect: router.currentRoute.value.fullPath }
            })
          }
        },
        {
          default: () => '编辑'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: {
            display: e.inStorage ? 'inline' : 'none'
          },
          onClick: () => {
            router.push({
              path: '/collection/process/stepPlan/processUpdate',
              query: { id: e.id,code:e?.itemCode, type: 0,typeIn:2,redirect: router.currentRoute.value.fullPath}//typeIn:1 入库
            })
          }
        },
        {
          default: () => '入库'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            router.push({
              path: '/collection/process/makeMenu/selfprocessDetail',
              query: { id: e.subItemCode, type: 1, code: e?.subItemCode, idSelf: e.id,redirect: router.currentRoute.value.fullPath } //编目审核详情
            })
          }
        },
        {
          default: () => '详情'
        }
      )
    ]
  }
]

const reset = () => {
  form.itemTypeCode = null
  form.itemName = null
  form.storageStatusCode = null
  form.catalogStatusCode = null
  form.assessStatusCode = null
  form.laidStatusCode = null
  form.recipient = null
  form.assetCode =null
  form.timeRange = null
  form.reviewType = null
  form.batchCode = null
  form.collectTypeCode = null
}
//筛选条件
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    queryTableData(true)
  }
})
const piciList = ref()
const banbenList = ref()
// 捐赠、购买、交换、拨交、罚没、呈缴
const collectFactionList: any = ref()
// 初审未审核，初审通过，初审不通过，终审未审核，终审通过，终审不通过
const statusList: any = ref()
const modalVisible = ref(false)
// 批量操作 同意，拒绝
const auditBatchOperationFn = async () => {
  const [error, res] = await sendRequest({
    module: 'dispose',
    api: 'approve',
    override: {
      data: {
        resultFlag: flagAudit.value,
        fromId: formIds.value?.join(','),
        opinions: reasonContent.value,
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  modalVisible.value = false
  reasonContent.value = null
  backId.value = null
  queryTableData()
}
const againBack = async () => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'collectItemsAssessfinalAuditBack',
    override: {
      params: {
        reviewOpinions: reasonContent.value,
        subItemCode: backId.value
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.msg)
  modalVisible.value = false
  reasonContent.value = null
  backId.value = null
  queryTableData()
}
const backId = ref()
//点击退回
const flagAudit = ref(false)//true 批量编目审核同意 false 批量编目审核拒绝
const handleDetail = (val: any,flag:any) => {
  console.log(val)
  // backId.value = val
  flagAudit.value = flag
  reasonContent.value = []//打开弹窗先清空内容
  modalVisible.value = true
}

//多选框勾选
type DataListSelectionsItem = {
  id: string
}
const notIssuedId = ref()
const dataListSelections: any = ref<DataListSelectionsItem[]>([])
const formIds = ref()
function selectionChangeHandle(val: any, info: any) {
  dataListSelections.value = val
  formIds.value = info?.map((i:any)=>i.fromId)||[]
  notIssuedId.value = []
  info.map((i: any) => {
    if (i.distributionStatus == '0') {
      notIssuedId.value.push(i.id)
    }
  })
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref()
const queryTableDataBefore = () => {
  queryTableData(true)
  // if (
  //   form.itemTypeCode ||
  //   form.itemName ||
  //   form.assessStatusCode ||
  //   form.batchCode ||
  //   form.collectTypeCode
  // ) {
  //   queryTableData()
  // } else {
  //   message.info('请输入查询条件')
  // }
}
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  formIds.value = []
  dataListSelections.value = []
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'collectingItemsList',
    override: {
      params: {
        ...form,
        recipientTimeStart: form.timeRange?.[0],
        recipientTimeEnd: form.timeRange?.[1],
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        listType: 2, //1 初编 编目 2 编目审核 3 藏品
        timeRange:null,
      }
    }
  })
  if (error) return message.error(error.message)
  const tmp: any = res.data
  tableData.value = tmp?.list
  paginationReactive.itemCount = tmp.totalCount
  console.log(paginationReactive.itemCount)
  tableLoading.value = false
}
const codeFn = async (code: any, refValue: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: code
      }
    }
  })
  if (error) return message.error(error.message)
  if(code=='A50')//编目审核-去掉未提交
  {
    refValue.value = res?.data?.map((it: any) => {
    return { value: it.dicCode, label: it.dicName }
  }).filter((it: any) => it.value != 'A5009')
  }
  else if(code=='A67')//入库审核-去掉通过
  {
    refValue.value = res?.data?.map((it: any) => {
    return { value: it.dicCode, label: it.dicName }
  }).filter((it: any) => it.value != 'A6704')
  }
  else{
    refValue.value = res?.data?.map((it: any) => {
    return { value: it.dicCode, label: it.dicName }
  })
  }
 
}
const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))
watch(
  () => route.path,
  () => {
    if (route.path == '/collection/process/stepPlan/index') 
    {
      queryTableData(true)
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
const formRules: FormRules = {
  userName: {
    required: true,
    trigger: 'blur',
    message: '用户名不能为空'
  }
}
const getTreeSelect = async () => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listTreeAll',
    override: {
      params: {
        statusCode: 'A4901'
      }
    }
  })
  if (error) return message.error(error.message)
  banbenList.value = res.data
}
const inStatusList = ref()
const laidOptions =  ref()
const menuList = ref()
onMounted(() => {
  getTreeSelect()
  codeFn('A50', statusList) //审核状态A50
  codeFn('A45', menuList) //编目状态A45
  codeFn('A46', inStatusList) //入藏状态A46
  codeFn('A47', piciList) //藏品状态A47
  codeFn('A67', laidOptions) //入库审核状态A67
  codeFn('A30', collectFactionList) //征集方式A30
  // queryTableData()
})
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="start">
        <NForm
          require-mark-placement="left"
          :show-feedback="false"
          label-placement="left"
        >
        <NSpace>
        <NFormItem label="批次编号:">
            <NInput
              placeholder="请输入批次编号"
              v-model:value="form.batchCode"
            />
          </NFormItem>
          <NFormItem label="藏品名称:">
            <NInput
              placeholder="请输入藏品名称"
              v-model:value="form.itemName"
            />
          </NFormItem>
          <NFormItem label="入藏状态:">
            <NSelect
              :options="inStatusList"
              v-model:value="form.storageStatusCode"
              placeholder="请选择入藏状态"
              clearable
              filterable
              style="width: 200px"
            />
          </NFormItem>

          <NFormItem label="征集方式:">
            <NSelect
              :options="collectFactionList"
              v-model:value="form.collectTypeCode"
              placeholder="请选择征集方式"
              clearable
              filterable
              style="width: 200px"
            />
          </NFormItem>
          <NFormItem label="版本类型:">
            <n-tree-select
              :options="banbenList"
              children-field="childList"
              key-field="classificationCode"
              label-field="classificationName"
              v-model:value="form.itemTypeCode"
              :render-option="renderOption"
              placeholder="请选择版本类型"
              clearable
              filterable
              style="width: 200px"
            />
          </NFormItem>
          <!-- <NFormItem label="编目状态:">
            <NSelect
              :options="menuList"
              v-model:value="form.catalogStatusCode"
              placeholder="请选择状态"
              clearable
              filterable
              style="width: 150px"
            />
          </NFormItem> -->

          <NFormItem label="编目审核状态:">
            <NSelect
              :options="statusList"
              v-model:value="form.assessStatusCode"
              placeholder="请选择编目审核状态"
              clearable
              filterable
              style="width: 200px"
            />
          </NFormItem>
          <NFormItem label="入库审核状态:">
            <NSelect
              :options="laidOptions"
              v-model:value="form.laidStatusCode"
              placeholder="请选择入库审核状态"
              clearable
              filterable
              style="width: 200px"
            />
          </NFormItem>
          
          <!-- <NFormItem label="批次:">
            <NSelect
              :options="piciList"
              v-model:value="form.batchCode"
              placeholder="请选择批次"
              clearable
              filterable
              style="width: 200px"
            />
          </NFormItem> -->

        <NFormItem label="领取人:">
            <NInput
             placeholder="输入领取人"             
             v-model:value="form.recipient"             
                  />      
           </NFormItem>            
           <NFormItem label="领取时间:">
                <NDatePicker
                  input-readonly
                  placeholder="请选择领取时间"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  v-model:formatted-value="form.timeRange"
                  style="width: 265px"
                  clearable
                />
              </NFormItem>
            <NFormItem label="审核查询:">
              <NSelect
                :options="[{label: '全部', value:0},{label:'仅我审核',value:1}]"
                v-model:value="form.reviewType"
                placeholder="请选择审核查询"
                clearable
                filterable
                style="width: 200px"
              />
            </NFormItem>
            <NFormItem label="资产码:">
            <NInput
             placeholder="输入资产码"             
             v-model:value="form.assetCode"             
                  />      
           </NFormItem>     
          <NFormItem>
            <NButton
              type="primary"
              style="width: 78px; margin-right: 10px"
              ghost
              @click="queryTableDataBefore()"
            >
              查询
            </NButton>
          </NFormItem>
          <NFormItem>
            <NButton
              style="width: 78px; margin-right: 10px"
              ghost
              @click="reset()"
              type="primary"
            >
              重置
            </NButton>
          </NFormItem>
       
        <NFormItem>
        <NButton
            color="#5FB17F"
            ghost
            @click="
              () =>
                router.push({
                  path: '/collection/process/StepPlan/pillContent',
                  query: { type: 2,redirect: router.currentRoute.value.fullPath } //2编目 1初编
                })
            "
          >
            批量入库
          </NButton>
        </NFormItem>
          <NButton
            color="#5FB17F"
            ghost
            @click="
              () =>
              handleDetail(formIds?.join(','),true)
            "
            :disabled="formIds.length ? false : true"
          >
            批量编目审核同意
          </NButton>
          <NButton
            color="red"
            ghost
            @click="
              () =>
              handleDetail(formIds?.join(','),false)
            "
            :disabled="formIds.length ? false : true"
          >
            批量编目审核拒绝
          </NButton>
        </NSpace>
        </NForm>
      </NSpace>
        <NSpace align="end">
         
          <!-- <NButton
            color="#5FB17F"
            ghost
            @click="
              () =>
                router.push({
                  path: '/collection/process/stepPlan/startApprove',
                  query: { id: dataListSelections?.join(','), type: 0 }
                })
            "
            :disabled="dataListSelections.length ? false : true"
          >
            批量终审
          </NButton>
          <NButton
            color="#5FB17F"
            ghost
            @click="
              () =>
                router.push({
                  path: '/collection/process/stepPlan/startApprove',
                  query: { id: dataListSelections?.join(','), type: 0 }
                })
            "
            :disabled="dataListSelections.length ? false : true"
          >
            批量初审
          </NButton> -->
          
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable
        v-bind="props"
        :bordered="false"
        :row-key="rowKey"
        :columns="columns"
        :data="tableData"
        :loading="tableLoading"
        :checked-row-keys="dataListSelections"
        @update:checked-row-keys="selectionChangeHandle"
      />
    </template>

    <template #pagination>
      <NPagination
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <!-- 批量同意和拒绝 -->
  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="auditBatchOperationFn"
      title="备注"
    >
      <div
        class="backA"
        style="width: 400rem;"
      >
        <!-- <div class="topTitle">审核退回</div> -->
        <NForm
          require-mark-placement="left"
          :model="form"
          :rules="formRules"
          ref="baseFormRef"
          label-placement="left"
          label-width="40"
        >
          <NFormItem
            label="备注"
            path="typeTree"
          >
            <NInput
              v-model:value="reasonContent"
              placeholder="备注"
              type="textarea"
              rows="5"
            />
          </NFormItem>
        </NForm>
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
.backA {
  .topTitle {
    font-size: 22px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: #5fb17f;
    // margin-bottom: 10rem;
  }
}
</style>
